<?php 
class IndexAction extends BaseAction{
	/**
	 * 文章列表
	 */
	public function index(){
		session('list_url',__SELF__);
		import("@.Util.Page");
		$where = array();
		$csign = null;
		if(isset($_GET['key']) && !empty($_GET['key'])){
			$key = $_GET['key'];
			$csign = M("ArticleType")->where("`key`='$key'")->find();
			$where['cid'] = array('eq',$csign['id']);
		}
		if(isset($_GET['kw']) && !empty($_GET['kw'])){
			$where['title'] = array('like','%'.$_GET['kw'].'%');
			$this->assign('kw',$_GET['kw']);
		}
		$cnt = D("Article")->where($where)->count();
		$page  = new Page($cnt,10);
		$page->setConfig('theme','%upPage% %linkPage% %downPage% ');
		$page->url = $csign['key'] ? 'index/'.$csign['key'] : 'index';
		$list = D("Article")->where($where)->order('created_at desc')->limit($page->firstRow.','.$page->listRows)->select();
		$top10 = D("Article")->field("id,title")->order('updated_at desc')->limit(10)->select();
		$this->assign('top10',$top10);
		$this->assign('list',$list);
		$this->assign('page',$page);
		$this->assign('csign',$csign);
		$this->display('index');
	}

	/**
	 * 文章详细
	 */
	public function detail(){
		$id = (int)$_GET['id'];
		$sign = M("Article")->where("id=$id")->find();
		$prev = M("Article")->where("id<$id")->order('id desc')->find();
		$next = M("Article")->where("id>$id")->order('id asc')->find();
		//相关文章
		$relation = M("Article")->field('id,title,created_at')->where()->limit(5)->select();
		//评论
		$count = D("Reply")->where("aid=$id")->count();
		$page_size = 7;
		$page_total = ceil($count/$page_size);
		$page = isset($_GET['page']) && intval($_GET['page']) > 0 ? intval($_GET['page']) : 1;
		$list = D("Reply")->where("aid=$id")->limit(($page-1)*$page_size.','.$page_size)->order('created_at desc')->select();
		$this->assign('page',$page);
		$this->assign('page_total',$page_total);
		$this->assign('prev',$prev);
		$this->assign('sign',$sign);
		$this->assign('next',$next);
		$this->assign('relation',$relation);
		$this->assign('list',$list);
		$this->display('detail');
	}

	/**
	 * 顶一下
	 */
	public function act_top(){
		$id = (int)$_POST['id'];
		$rst = D("Article")->where("id=$id")->setInc('top_count',1);
		if($rst!==false)
			$this->ajaxReturn('','顶文成功',1);
		else
			$this->ajaxReturn('','顶文失败',0);
	}

	/**
	 * 评论
	 */
	public function reply(){
		$act = D("Reply");
		if($act->create()){
			$rst = $act->add();
			if($rst!==false){
				D("Article")->where("id=".$_POST['aid'])->setInc('reply_count',1);
				$this->ajaxReturn('','留言成功',1);
			}else{
				$this->ajaxReturn('','留言失败:'.$act->getLastSql(),0);
			}
		}else{
			$this->ajaxReturn('','验证失败:'.$act->getError(),0);
		}
	}
}
?>